package com.example.coursehub.course.repository;

import com.example.coursehub.course.entity.Chapter;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.util.List;

/**
 * 章节数据访问层
 */
@Repository
public interface ChapterRepository extends JpaRepository<Chapter, String> {

    /**
     * 根据课程ID查询章节（按排序号排序）
     */
    @Query("SELECT c FROM Chapter c WHERE c.course.courseId = :courseId ORDER BY c.sortOrder ASC")
    List<Chapter> findByCourseIdOrderBySortOrder(@Param("courseId") String courseId);

    /**
     * 根据课程ID和状态查询章节
     */
    @Query("SELECT c FROM Chapter c WHERE c.course.courseId = :courseId AND c.status = :status ORDER BY c.sortOrder ASC")
    List<Chapter> findByCourseIdAndStatus(@Param("courseId") String courseId, @Param("status") Integer status);

    /**
     * 根据章节名称模糊查询
     */
    List<Chapter> findByChapterNameContaining(String chapterName);

    /**
     * 统计课程的章节数量
     */
    @Query("SELECT COUNT(c) FROM Chapter c WHERE c.course.courseId = :courseId")
    Long countByCourseId(@Param("courseId") String courseId);

    /**
     * 查询课程中最大的排序号
     */
    @Query("SELECT MAX(c.sortOrder) FROM Chapter c WHERE c.course.courseId = :courseId")
    Integer findMaxSortOrderByCourseId(@Param("courseId") String courseId);

    /**
     * 根据课程ID批量删除章节
     */
    void deleteByCourse_CourseId(String courseId);
}